<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <p>我的订单</p>
    </header>

    <!-- 订单列表部分 -->
    <h3>未支付订单信息：</h3>
    <ul class="order">
      <template v-for="item in orderArr" :key="item.id">
        <li v-if="item.orderState === 0">
          <div class="order-info">
            <p>
              {{ item.business?.businessName }}
              <i
                  class="fa fa-caret-down"
                  :class="{ rotated: item.showDetail }"
                  @click="toggleOrderDetail(item)"
              ></i>
            </p>
            <div class="order-info-right">
              <div
                  class="order-info-right-icon"
                  @click="goToPayment(item.id)"
              >
                去支付
              </div>
            </div>
          </div>
          <ul class="order-detailet" v-show="item.showDetail">
            <li v-for="(odItem, index) in item.orderDetails" :key="index">
              <p>{{ getDisplayFoodName(odItem) }} x {{ odItem.quantity }}</p>
              <p>&#165;{{ formatPrice(getDisplayFoodPrice(odItem) * odItem.quantity) }}</p>
            </li>
            <li>
              <p>配送费</p>
              <p>&#165;{{ formatPrice(getDisplayDeliveryPrice(item)) }}</p>
            </li>
            <li class="order-total">
              <p>总计</p>
              <p>&#165;{{ formatPrice(calculateOrderTotal(item)) }}</p>
            </li>
          </ul>
        </li>
      </template>
      <li v-if="unpaidOrders.length === 0" class="no-orders">
        <p>暂无未支付订单</p>
      </li>
    </ul>

    <h3>已支付订单信息：</h3>
    <ul class="order">
      <template v-for="item in orderArr" :key="item.id">
        <li v-if="item.orderState === 1 || item.orderState===2">
          <div class="order-info">
            <p>
              {{ item.business?.businessName }}
              <i
                  class="fa fa-caret-down"
                  :class="{ rotated: item.showDetail }"
                  @click="toggleOrderDetail(item)"
              ></i>
            </p>
            <div class="order-info-right">
              <span class="order-state">已支付</span>
              <div class="order-info-right-icon" @click="confirmReceipt(item.id)">
                确认收货
              </div>
            </div>
          </div>
          <ul class="order-detailet" v-show="item.showDetail">
            <li v-for="(odItem, index) in item.orderDetails" :key="index">
              <p>{{ getDisplayFoodName(odItem) }} x {{ odItem.quantity }}</p>
              <p>&#165;{{ formatPrice(getDisplayFoodPrice(odItem) * odItem.quantity) }}</p>
            </li>
            <li>
              <p>配送费</p>
              <p>&#165;{{ formatPrice(getDisplayDeliveryPrice(item)) }}</p>
            </li>
            <li class="order-total">
              <p>总计</p>
              <p>&#165;{{ formatPrice(calculateOrderTotal(item)) }}</p>
            </li>
            <li class="order-date">
              <p>下单时间</p>
              <p>{{ formatDate(item.orderDate) }}</p>
            </li>
          </ul>
        </li>
      </template>
      <li v-if="paidOrders.length === 0" class="no-orders">
        <p>暂无已支付订单</p>
      </li>
    </ul>

    <h3>已完成订单信息：</h3>
    <ul class="order">
      <template v-for="item in orderArr" :key="item.id">
        <li v-if="item.orderState === 3">
          <div class="order-info">
            <p>
              {{ item.business?.businessName }}
              <i
                  class="fa fa-caret-down"
                  :class="{ rotated: item.showDetail }"
                  @click="toggleOrderDetail(item)"
              ></i>
            </p>
            <div class="order-info-right">
              <span class="order-state">已完成</span>
            </div>
          </div>
          <ul class="order-detailet" v-show="item.showDetail">
            <li v-for="(odItem, index) in item.orderDetails" :key="index">
              <p>{{ getDisplayFoodName(odItem) || '未知商品' }} x {{ odItem.quantity }}</p>
              <p>&#165;{{ formatPrice(getDisplayFoodPrice(odItem) * odItem.quantity) }}</p>
            </li>
            <li>
              <p>配送费</p>
              <p>&#165;{{ formatPrice(getDisplayDeliveryPrice(item)) }}</p>
            </li>
            <li class="order-total">
              <p>总计</p>
              <p>&#165;{{ formatPrice(calculateOrderTotal(item)) }}</p>
            </li>
            <li class="order-date">
              <p>下单时间</p>
              <p>{{ formatDate(item.orderDate) }}</p>
            </li>
          </ul>
        </li>
      </template>
      <li v-if="completedOrders.length === 0" class="no-orders">
        <p>暂无已完成订单</p>
      </li>
    </ul>

    <!-- 底部菜单部分 -->
    <Footer />
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {useRouter} from 'vue-router'
import {orderAPI} from '@/api/order.js'
import { walletAPI } from '@/api/wallet.js'
import Footer from "../components/Footer.vue"

const router = useRouter()
const orderArr = ref([])
const loadingOrders = ref(new Set())

// 计算属性：未支付订单
const unpaidOrders = computed(() => {
  return orderArr.value.filter(order => order.orderState === 0)
})

// 计算属性：已支付订单
const paidOrders = computed(() => {
  return orderArr.value.filter(order => order.orderState === 1|| order.orderState===2)
})

// 计算属性：已完成订单
const completedOrders = computed(() => {
  return orderArr.value.filter(order => order.orderState === 3)
})

// 安全的价格格式化函数
const formatPrice = (price) => {
  const num = Number(price)
  if (isNaN(num)) {
    return '0.00'
  }
  return num.toFixed(2)
}

// 获取显示用的商品名称（优先使用快照）
const getDisplayFoodName = (orderDetail) => {
  return orderDetail?.foodNameSnapshot || orderDetail?.food?.foodName || '未知商品'
}

// 获取显示用的商品价格（优先使用快照）
const getDisplayFoodPrice = (orderDetail) => {
  const price = orderDetail?.foodPriceSnapshot || orderDetail?.food?.foodPrice
  return Number(price) || 0
}

// 获取显示用的配送价格（基于订单对象）
const getDisplayDeliveryPrice = (order) => {
  // 尝试从订单详情快照获取，如果没有则从商家信息获取
  const snapshotPrice = order?.orderDetails?.[0]?.deliverPrinceSnapshot
  if (snapshotPrice !== undefined && snapshotPrice !== null) {
    return Number(snapshotPrice)
  }
  const businessPrice = order?.business?.deliveryPrice
  return Number(businessPrice) || 0
}

// 计算订单总计
const calculateOrderTotal = (order) => {
  const foodTotal = Number(order?.orderTotal) || 0
  const deliveryPrice = getDisplayDeliveryPrice(order)
  return foodTotal + deliveryPrice
}

// 切换订单详情显示
const toggleOrderDetail = async (order) => {
  try {
    // 如果当前没有显示详情，并且订单详情数据不完整，则从接口获取
    if (!order.showDetail && (!order.orderDetails || order.orderDetails.length === 0 || !order.orderDetails[0]?.food)) {
      await loadOrderDetail(order.id)
    }

    // 使用 Object.assign 确保响应式更新
    const orderIndex = orderArr.value.findIndex(o => o.id === order.id)
    if (orderIndex !== -1) {
      orderArr.value[orderIndex].showDetail = !orderArr.value[orderIndex].showDetail
    }
  } catch (error) {
    console.error('切换订单详情失败:', error)
  }
}

// 加载单个订单的详细信息
const loadOrderDetail = async (orderId) => {
  if (loadingOrders.value.has(orderId)) return
  try {
    loadingOrders.value.add(orderId)

    const response = await orderAPI.getOrderById(orderId)

    if (response.data && response.data.data) {
      const orderDetailData = response.data.data
      console.log("orderdetail", orderDetailData)
      const orderIndex = orderArr.value.findIndex(order => order.id === orderId)
      if (orderIndex !== -1) {
        // 统一处理订单详情数据格式
        const updatedOrder = {
          ...orderArr.value[orderIndex],
          orderDetails: Array.isArray(orderDetailData)
              ? orderDetailData.map(detail => ({
                ...detail,
                food: detail.food || detail.data?.food || null
              }))
              : [],
          business: orderDetailData.business || orderArr.value[orderIndex].business,
          orderTotal: orderDetailData.orderTotal || orderArr.value[orderIndex].orderTotal,
          orderDate: orderDetailData.orderDate || orderArr.value[orderIndex].orderDate
        }

        // 使用 Vue 的响应式更新
        orderArr.value[orderIndex] = updatedOrder
      }
    }
  } catch (error) {
    console.error(`加载订单 ${orderId} 详情失败:`, error)
  } finally {
    loadingOrders.value.delete(orderId)
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化错误:', error)
    return ''
  }
}

// 去支付
const goToPayment = (orderId) => {
  router.push({
    path: '/payment',
    query: { orderId: orderId }
  })
}

// 确认收货
const confirmReceipt = async (orderId) => {
  if (!confirm('是否确认收货？')) {
    return;
  }

  try {
    const response = await walletAPI.confirmReceipt({ orderId: orderId });

    if (response.data && response.data.success !== false) {
      alert('确认收货成功！');
      // 刷新订单列表
      await loadOrders();
    } else {
      alert('确认收货失败：' + (response.data.message || '请重试'));
    }
  } catch (error) {
    console.error('确认收货失败:', error);
    alert('确认收货失败，请重试');
  }
}

// 加载订单列表数据
const loadOrders = async () => {
  try {
    const userId = parseInt(sessionStorage.getItem('userId'))
    const params = {
      userId: userId
    }
    const response = await orderAPI.listOrdersByUserId(params)

    if (response.data && Array.isArray(response.data)) {
      // 处理订单数据，添加显示详情的状态
      orderArr.value = response.data.map(order => ({
        ...order,
        showDetail: false,
        orderDetails: order.orderDetails || []
      }))
    } else {
      console.error('订单数据格式错误:', response)
      orderArr.value = []
    }
  } catch (error) {
    console.error('加载订单列表失败:', error)
    orderArr.value = []
  }
}

// 页面加载时获取订单数据
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/****************** header部分 ******************/
.wrapper header {
  flex:0.12;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

/****************** 历史订单列表部分 ******************/
.wrapper h3 {
  box-sizing: border-box;
  padding: 4vw;
  font-size: 4vw;
  font-weight: 300;
  color: #999;
  background-color: #f5f5f5;
  margin-bottom: 0;
}

.wrapper .order li {
  border-bottom: 1px solid #eee;
}

.wrapper .order li .order-info {
  box-sizing: border-box;
  padding: 3vw 4vw;
  font-size: 4vw;
  color: #666;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
}

.wrapper .order li .order-info p {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 2vw;
}

.wrapper .order li .order-info .fa-caret-down {
  cursor: pointer;
  color: #999;
  transition: transform 0.3s ease;
}

.wrapper .order li .order-info .fa-caret-down:hover {
  color: #0097ff;
}

.wrapper .order li .order-info .order-info-right {
  display: flex;
  align-items: center;
  gap: 3vw;
}

.wrapper .order li .order-info .order-info-right .order-info-right-icon {
  background-color: #f90;
  color: #fff;
  border-radius: 3px;
  padding: 1vw 2vw;
  user-select: none;
  cursor: pointer;
  font-size: 3.5vw;
}

.wrapper .order li .order-info .order-info-right .order-info-right-icon:hover {
  background-color: #e68900;
}

.wrapper .order li .order-info .order-info-right .order-state {
  color: #38ca73;
  font-size: 3.5vw;
  font-weight: bold;
}

.wrapper .order li .order-detailet {
  width: 100%;
  background-color: #f9f9f9;
  padding: 2vw 0;
}

.wrapper .order li .order-detailet li {
  width: 100%;
  box-sizing: border-box;
  padding: 1.5vw 4vw;
  color: #666;
  font-size: 3.5vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .order li .order-detailet .order-total {
  border-top: 1px dashed #ddd;
  font-weight: bold;
  color: #333;
  margin-top: 1vw;
  padding-top: 2vw;
}

.wrapper .order li .order-detailet .order-date {
  color: #999;
  font-size: 3vw;
}

.no-orders {
  text-align: center;
  padding: 8vw 4vw;
  color: #999;
  font-size: 4vw;
  background-color: #fff;
}

/* 旋转动画 */
.wrapper .order li .order-info .fa-caret-down.rotated {
  transform: rotate(180deg);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wrapper .order li .order-info {
    padding: 4vw 4vw;
  }

  .wrapper .order li .order-detailet li {
    padding: 2vw 4vw;
  }
}
</style>